package edu.ccit.shudong.controller;

import edu.ccit.shudong.entity.Comment;
import edu.ccit.shudong.service.ICommentService;
import edu.ccit.shudong.service.IUserService;
import edu.ccit.shudong.utils.JwtUtils;
import edu.ccit.shudong.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Suting Luo
 * @since 2024-06-14
 */
@RestController
@RequestMapping("/comments")

@CrossOrigin(origins = "http://localhost:9090", originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT})

@Api(tags = "评论")
public class CommentController {
    @Autowired
    private ICommentService commentService;

    @Autowired
    private IUserService userService;

    @ApiOperation("评论列表")
    @GetMapping("/{postId}")
    public Object getList(@ApiParam(value = "帖子ID", name = "postId", required = true)@PathVariable("postId") Long postId) {
        List<Comment> comments = commentService.findListByPostId(postId);
        return comments != null ? R.ok("成功", comments) : R.error("失败");
    }

    @ApiOperation("本人的私信")
    @GetMapping("/{postId}/{userId}")
    public Object getmyList(@ApiParam(value = "用户ID", name = "userId", required = true)@PathVariable("userId") Long userId,
                            @ApiParam(value = "帖子ID", name = "postId", required = true) @PathVariable("postId") Long postId) {
        List<Comment> comments = commentService.findListByUserId(userId);
        return comments != null ? R.ok("成功", comments) : R.error("失败");
    }

    @ApiOperation("评论添加")
    @PostMapping
    public Object addOne(
            HttpServletRequest request,
            @ApiParam(value = "内容", name = "content", required = true) @RequestParam("content") String content,
            @ApiParam(value = "帖子ID", name = "postId", required = true)@RequestParam("postId") Long postId) {
        String token = request.getHeader("Authorization");
        Long userId = JwtUtils.getUserId(token);
        if (userId == null || userId <= 0) return R.error("用户登录已失效，请重新登录");
        if (content.trim().isEmpty()) return R.error("内容不能为空");
        if (content.length() > 150) content = content.substring(0, 150);
        Comment comment = commentService.addOne(userId, postId, content);
        return comment != null ? R.ok("评论添加成功", comment) : R.error("评论添加失败");
    }
}
